#include "utils.h"
using namespace FsxWsUtils;

//
// Difference in seconds to UTC
//
const int Utils::utcDifferenceS() {
    QDateTime utcDt = QDateTime::currentDateTimeUtc();
    // does not work if using msecsTo on QDateTime, need to convert to times first!
    // act on the same Date/time to avoid unexpected differences!
    QTime myTime  = utcDt.toLocalTime().time();
    QTime utcTime = utcDt.time();
    qint64 diff = utcTime.msecsTo(myTime);
    int d = diff / 1000;
    return d;
}

//
// Difference in hh:mm to UTC
//
const QString Utils::utcDifferenceHourMin() {
    int diff = Utils::utcDifferenceS();
    if (diff == 0) return "+00:00";
    int h = diff / 3600;
    int m = (diff - (h * 3600)) / 60;
    QString hhmm = QString("%1:%2").arg(h,2,10,QChar('0')).arg(m,2,10,QChar('0'));
    hhmm.prepend(diff < 0 ? '-' : '+');
    return hhmm;
}

//
// String to boolean
//
const bool Utils::stringToBoolean(QString boolCandidate) {
    if (boolCandidate.isEmpty()) return false;
    if (boolCandidate.startsWith('t', Qt::CaseInsensitive) || boolCandidate.startsWith('y', Qt::CaseInsensitive) ) return true;
    return false;
}

//
// Now - timeFrameMs timestamp
//
const qint64 Utils::timeframe(const qint64 timeFrameMs)
{
    qint64 tf = QDateTime::currentMSecsSinceEpoch() - timeFrameMs;
    return tf;
}

//
// YYYY dd mm hh:mm:ss timestamp
//
const QString Utils::timestamp(bool utc) {
    QDateTime dt = QDateTime::currentDateTime();
    if (utc) dt = dt.toUTC();
    QString ts = dt.toString("yyyyMMdd hh:mm:ss");
    return ts;
}

//
// Check a Navigraph directory
//
const bool Utils::isValidFmcDataDirectory(QString directory) {
    if (directory.isEmpty()) return false;
    if (!QDir(directory).exists()) return false;
    if (!directory.endsWith('/')) directory.append('/');
    directory.append("SIDSTARS");
    return QDir(directory).exists();
}
